<?php
namespace app\system\model;
use \think\Model;
use think\Db;
use app\member\model\Member;

class Login extends Base{
    /**
     * 登录认证
     */
    public function login_check($data=[]){
        return true;
        //$mall_domain = \app\common\model\Base::get_domain_set('mall_domain',1);
        //return $this->login_com_check($data,$mall_domain.'/api/shoplogin/login_new');
    }
    public function login_test_check($data=[]){
        $mall_domain = \app\common\model\Base::get_domain_set();
        $get_token_config = [
            'client_id'  =>'ada75hfsdt834hg83gj43',
            'app_secret' =>  'dfh237rv2guvg2ngu349g3',
            'redirect_url' => preg_http($mall_domain['curl_api']).'/oauth/oauth/index',
            'username' => $data['username'],
            'password' => $data['password'],
            'response_type' => 'code'
        ];
//        echo json_encode($mall_domain);die;
        $output = \app\common\model\Base::api_http(preg_http($mall_domain['ucenter_url']).'/client/auth/sys_asyn_login',json_encode($get_token_config));
        if(!empty($output)) $output = \app\common\model\Base::object_array($output);
        print_r($output);die;
    }
    public function oauth_check($data=[]){
        $mall_domain = \app\common\model\Base::get_domain_set('mall_domain',1);
        return $this->login_com_check($data,$mall_domain.'/api/oauth_member/get_user_info');
    }
    public function login_com_check($data=[],$url){
        $output = \app\common\model\Base::curl_post($url,$data);
        $output = \app\common\model\Base::object_array($output);
        if($output['code'] > 0){
            $web_set = $output['data'];
            $web_set['admin_uid'] = $web_set['customer_id']??0;
            $web_set['addtime'] = time();
            $web_set['identify'] = 0;
            unset($web_set['uid']);
            //登录成功，需要返回网站信息和token
            $web_set['token'] =  md5(create_random().request()->time().$web_set['username']??'');
            if(!empty($web_set['web_list'])){
                $web_set['is_wms'] = 1;
            }
            //token文件写入
            $this->token_recode($web_set);
            if(!empty($data['is_show'])){
                $web_set['info'] = $web = \app\system\model\Login::get_login_token($web_set['token']);
            }
            //token信息写入
            return $web_set;
        }else{
            return $output['code'];
        }
    }

    /**
     * @param array $data
     * token 文件写入缓存
     */
    public function token_recode($data=[]){
        $option = config('cache');
        $option['path'] = $option['path'];
        //缓存时间半个小时 30*3600=108000
        $time = request()->time();
       // $option['expire'] = $data['expire'] = $time+108000;
        cache($data['token'],$data,$option);
        cache("web_token_file_".config('web_id'),$data,$option);
//        session_set_cookie_params();
    }
    function post_check($post)
    {
        if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否为打开
        {
            $post = addslashes($post); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤
        }
        $post = str_replace("_", "＼_", $post); // 把 '_'过滤掉
        $post = str_replace("%", "＼%", $post); // 把' % '过滤掉
       /* $post = strtr ( $post, array (
            "%" => "\%",
            "_" => "\_"
        ) );*/
        $post = nl2br($post); // 回车转换
        $post= htmlspecialchars($post); // html标记转换
        return $post;
    }
    // 富文本编辑器防XSS
    function clean_xss_html($html){
        $allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|object|param|embed';
        $skipkeys = array('onabort','onactivate','onafterprint','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate','onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforeunload','onbeforeupdate','onblur','onbounce','oncellchange','onchange','onclick','oncontextmenu','oncontrolselect','oncopy','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick','ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','ondragstart','ondrop','onerror','onerrorupdate','onfilterchange','onfinish','onfocus','onfocusin','onfocusout','onhelp','onkeydown','onkeypress','onkeyup','onlayoutcomplete','onload','onlosecapture','onmousedown','onmouseenter','onmouseleave','onmousemove','onmouseout','onmouseover','onmouseup','onmousewheel','onmove','onmoveend','onmovestart','onpaste','onpropertychange','onreadystatechange','onreset','onresize','onresizeend','onresizestart','onrowenter','onrowexit','onrowsdelete','onrowsinserted','onscroll','onselect','onselectionchange','onselectstart','onstart','onstop','onsubmit','onunload','javascript','script','eval','behaviour','expression','style','class');
        preg_match_all("/\<([^\<]+)\>/is", $html, $ms);
        if($ms[1]) {
            $ms[1] = array_unique($ms[1]);
            foreach ($ms[1] as $value) {
                $searchs[] = "<".$value.">";
                $value = htmlspecialchars($value);
                $value = str_replace(array('\\','/*'), array('.','/.'), $value);
                $skipstr = implode('|', $skipkeys);
                $value = preg_replace(array("/($skipstr)/i"), '.', $value);
                if(!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
                    $value = '';
                }
                $replaces[] = empty($value)?'':"<".str_replace('&quot;', '"', $value).">";
            }
        }
        $html = str_replace($searchs, $replaces, $html);
        return $html;
    }

    /******
     *
     * 设置门店固定菜单
     * $templet_id  模板id
     */
    public function set_multishop_menus($site_type){
        if(!empty($site_type)){
            switch ($site_type){
                case 1:
                    $data = [
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>1,
                            'name'=>'平台员工',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>2,
                            'name'=>'普通用户',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],
                    ];
                    foreach($data as $v){
                        $new_type_id = model('member/MemberType')->relationCreate($v,0);
                    }

                    break;
                case 2:
                    $data = [
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>1,
                            'name'=>'平台员工',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>2,
                            'name'=>'普通用户',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>3,
                            'name'=>'门店',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],
                        [
                            'web_id'=>config('web_id'),
                            'lang_id'=>config('lang_id')??1,
                            'identify'=>4,
                            'name'=>'门店员工',
                            'is_system'=>1,
                            'is_need_review'=>0,
                            'page_type'=>'',
                            'status'=>1,
                            'pic'=>'',
                            'addtime'=>request()->time()
                        ],

                    ];

                    $menu_ids = Db::name('front_power')->where(['web_id'=>0,'site_type'=>2,'member_type'=>3])->column('id');
                    $menu_ids = implode(',',$menu_ids);
                    foreach($data as $v){
                        $new_type_id = model('member/MemberType')->relationCreate($v,0);
                        if($v['identify']==3){
                            $member_power = [
                                'web_id'=>config('web_id'),
                                'lang_id'=>config('lang_id')??1,
                                'type_id'=>$new_type_id,
                                'level_id'=>0,
                                'manage'=>$menu_ids,
                                'update_time'=>request()->time()
                            ];
                            $member_type_level = [
                                'uid'=>0,
                                'type_id'=>$new_type_id,
                                'level_id'=>0,
                            ];
                            $ok = Db::name('member_power')->insert($member_power);
                            Db::name('member_type_level')->insert($member_type_level);
                        }

                    }
                    break;
            }
            $web_info = Db::connect(config('database.db_config2'))->name('web_set')->where(['web_id'=>config('web_id'),'lang_id'=>config('lang_id')])->find();
            $shop_info = [
                'uid'=>0,
                'shop_name'=>$web_info['name']??'',
                'shop_logo'=>$web_info['logo']??'',
                'address'=>$web_info['address']??'',
                'url'=>$web_info['url']??'',
                'add_time'=>request()->time(),
                'web_id'=>config('web_id'),
                'lang_id'=>config('lang_id'),
                'summary'=>$web_info['descript']??'',
                'phone'=>$web_info['tel']??'',
            ];
            Db::name('multishop_info')->insert($shop_info);
        }else{
            return false;
        }
    }

    /**
     * @param $token
     * @return array|mixed
     * 获取登录信息
     * 公共的获取方法,方便修改登录信息存储,不用修改太多的地方
     */
    static public function get_login_token($token){
        if(empty($token)) return false;
        $login_info = cache($token,'',get_cache_path(false));
        return $login_info??[];
    }

    /*******
     * @param array $data
     * @return mixed
     */
    static public function get_site_type($data=[]){
        $mall_domain = \app\common\model\Base::get_domain_set('mall_domain',1);
        $url = $mall_domain.'/api/web/get_web_site';
        $output = \app\common\model\Base::curl_post($url,$data);
        $output = \app\common\model\Base::object_array($output);
        if($output['code']==200){
            return $site_type = $output['data']['site_type'];
        }else{
            return -11407;
        }

    }

    /**
     * @param $token
     * @return bool
     * 删除登录信息
     */
    static public function del_login_token($token){
        if(empty($token)) return false;
        $login_info = cache($token,NULL,get_cache_path(false));
    }

    /**
     * @param $token
     * @param $data
     * @return bool
     * 更新缓存
     */
    static public function update_login_token($token,$data){
        if(empty($token) || empty($data)) return false;
        cache($token,$data,get_cache_path(false));
    }
}